package com.example.shuqishixi;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import org.json.JSONArray;
import org.json.JSONObject;

@WebServlet(name = "GetUserInfoServlet", value = "/getUserInfoServlet")
public class GetUserInfoServlet extends HttpServlet {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456";

    // 添加静态块验证数据库驱动加载
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("[INIT] MySQL JDBC Driver 加载成功");
        } catch (ClassNotFoundException e) {
            System.err.println("[INIT ERROR] MySQL JDBC Driver not found");
            throw new RuntimeException("MySQL JDBC Driver not found", e);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();

        String action = request.getParameter("action");
        String queryUsername = request.getParameter("username");
        String roleParam = request.getParameter("role"); // 修改参数名为role，与前端保持一致
        String sessionUsername = (String) request.getSession().getAttribute("username");
        String sessionRole = (String) request.getSession().getAttribute("user_role");

        // 增强会话验证调试
        System.out.println("\n[DEBUG] ===== 开始处理请求 =====");
        System.out.println("[DEBUG] 请求参数 - action: " + action +
                ", username: " + queryUsername +
                ", role: " + roleParam);
        System.out.println("[DEBUG] Session验证 - username: " + sessionUsername +
                ", user_role: " + sessionRole);

        // 检查用户是否登录
        if (sessionUsername == null) {
            System.out.println("[ERROR] 用户未登录");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            out.write("{\"error\":\"用户未登录\"}");
            return;
        }

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            System.out.println("[DEBUG] 数据库连接成功");

            // 处理按角色获取用户列表的请求
            if ("getUsersByRole".equals(action) && roleParam != null) {
                System.out.println("[DEBUG] 处理按角色获取用户列表请求");

                // 权限验证
                if (!"admin".equals(sessionRole)) {
                    System.out.println("[ERROR] 非管理员尝试访问用户列表");
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                    out.write("{\"error\":\"无权访问用户列表\"}");
                    return;
                }

                JSONObject result = new JSONObject();
                JSONArray users = new JSONArray();

                String sql = "SELECT username, email, phone, user_role FROM users WHERE user_role = ?";
                System.out.println("[DEBUG] 准备执行SQL: " + sql);
                System.out.println("[DEBUG] 查询参数 - user_role: " + roleParam);

                try (PreparedStatement ps = conn.prepareStatement(sql)) {
                    ps.setString(1, roleParam);
                    ResultSet rs = ps.executeQuery();

                    System.out.println("[DEBUG] 开始遍历结果集");
                    int userCount = 0;

                    while (rs.next()) {
                        userCount++;
                        JSONObject user = new JSONObject();
                        user.put("username", rs.getString("username"));
                        user.put("email", rs.getString("email"));
                        user.put("phone", rs.getString("phone"));
                        user.put("user_role", rs.getString("user_role"));
                        users.put(user);

                        System.out.println("[DEBUG] 找到用户 #" + userCount + ": " + user.toString());
                    }

                    System.out.println("[DEBUG] 共找到 " + userCount + " 个用户");
                    result.put("users", users);

                    // 添加成功状态
                    result.put("success", true);
                    result.put("count", userCount);
                }

                String jsonResponse = result.toString();
                System.out.println("[DEBUG] 准备返回JSON响应: " + jsonResponse);
                out.write(jsonResponse);
                return;
            }

            // 处理获取单个用户信息的请求
            if (queryUsername != null) {
                System.out.println("[DEBUG] 处理获取单个用户信息请求");

                // 权限验证
                if (!"admin".equals(sessionRole) && !queryUsername.equals(sessionUsername)) {
                    System.out.println("[ERROR] 无权限查看其他用户信息");
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                    out.write("{\"error\":\"无权查看该用户信息\"}");
                    return;
                }

                getUserInfo(conn, queryUsername, out);
                return;
            }

            // 默认返回当前用户信息
            System.out.println("[DEBUG] 处理获取当前用户信息请求");
            getUserInfo(conn, sessionUsername, out);

        } catch (SQLException e) {
            System.err.println("[ERROR] 数据库操作异常: " + e.getMessage());
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write("{\"error\":\"数据库查询失败: " + e.getMessage() + "\"}");
        } finally {
            System.out.println("[DEBUG] ===== 请求处理完成 =====");
        }
    }

    private void getUserInfo(Connection conn, String username, PrintWriter out) throws SQLException {
        String sql = "SELECT username, email, phone, user_role FROM users WHERE username = ?";
        System.out.println("[DEBUG] 执行用户查询: " + sql);
        System.out.println("[DEBUG] 查询参数 - username: " + username);

        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, username);
            ResultSet rs = ps.executeQuery();

            JSONObject responseJson = new JSONObject();

            if (rs.next()) {
                JSONObject userJson = new JSONObject();
                userJson.put("username", rs.getString("username"));
                userJson.put("email", rs.getString("email"));
                userJson.put("phone", rs.getString("phone"));
                userJson.put("user_role", rs.getString("user_role"));

                responseJson.put("success", true);
                responseJson.put("user", userJson);

                System.out.println("[DEBUG] 找到用户信息: " + userJson.toString());
            } else {
                System.out.println("[DEBUG] 未找到用户信息");
                responseJson.put("success", false);
                responseJson.put("error", "用户信息不存在");
            }

            out.write(responseJson.toString());
        }
    }
}
